package com.hiwan.framework.exception;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.hiwan.platform.util.StackTraceUtil;

/**
 * 
 * Datetime   ： 2016年2月2日 下午1:34:25<br>
 * Title      :  HiwanSimpleMappingExceptionResolver.java<br>
 * Description:   通用异常处理<br>
 * Company    :  hiwan<br>
 * @author cbj
 *
 */
public class HiwanSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {

		String viewName = determineViewName(ex, request);
		logger.error(StackTraceUtil.getStackTrace(ex));
		if (viewName != null) {
			// JSP格式返回
			// 本系统大多数页面通过jquery load方法加载，也是ajax请求，无法通过 request.getHeader("X-Requested-With") != null来区分
			if (!(request.getHeader("accept").indexOf("application/json") > -1)) {
				// 如果不是异步请求
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}
				return getModelAndView(viewName, ex, request);
			} else {
				// JSON格式返回
				try {
					//response.setStatus(500);
					PrintWriter writer = response.getWriter();
					//writer.write("操作失败:" + ex.getMessage());
					writer.write("操作失败，请联系管理员！");
					writer.flush();
				} catch (IOException e) {
					logger.error(StackTraceUtil.getStackTrace(e));
				}
				return null;

			}
		} else {
			return null;
		}
	}
}
